/**
 * 常用工具
 * */

import { baseUrl } from '../config'
const app = getApp()

/**
 * @desc    请求方法
 * @param   {Object}  requestParams  请求参数
 * requestParams说明：
 *  url 请求地址
 *  method  请求方式，默认为GET，需大写
 *  data  post发送的数据
 *  params  get发送的数据
 *  headers 请求头
 *  dataType  同官方说明
 *  responseType  同官方说明
 *  success  成功回调
 *  fail  失败回调
 *  complete  完成回调
 * */
function request(requestParams) {
  let url = `${baseUrl}${requestParams.url}`;
  let method = requestParams.method || 'GET';
  let data = requestParams.data || {};
  let params = requestParams.params || {};
  let headers = requestParams.headers || {};
  let dataType = requestParams.dataType;
  let responseType = requestParams.responseType;
  let success = requestParams.success;
  let fail = requestParams.fail;
  let complete = requestParams.complete;
  if (app.globalData.userInfo.access_token) {
    headers.Authorization = `${app.globalData.userInfo.token_type}${app.globalData.userInfo.access_token}`
  }

  // 处理url参数
  if (!isEmptyObject(params)) {
    let paramsArr = [];
    for (let key in params) {
      paramsArr.push(`${key}=${params[key]}`);
    }
    if (url.indexOf("?") !== -1) {
      url += paramsArr.join('&')
    } else {
      url += `?${paramsArr.join('&')}`
    }
  }
  wx.request({
    url: url,
    method: method,
    data: data,
    header: headers,
    dataType: dataType,
    responseType: responseType,
    success: function({ data }) {
      if(data.code === 401){
        try {
          wx.removeStorageSync("userInfo");
        } catch (e) {}
        app.globalData.userInfo = {}
        wx.switchTab({
          url: '/pages/mine/index'
        })
      }
      success(data);
    },
    fail: function(err) {
      fail && fail(err);
    },
    complete: complete
  });
}

/**
 * @desc  验证对象是否为空对象
 * @param {Object} obj 需要验证的对象
 * */
function isEmptyObject(obj) {
  return JSON.stringify(obj) === "{}";
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @desc   判断是否为手机号
 * @param  {String|Number} str
 * @return {Boolean}
 */
function isPhoneNum(str) {
  return /^(\+?0?86\-?)?1[3456789]\d{9}$/.test(str)
}

module.exports = {
  isEmptyObject,
  request,
  parseTime,
  isPhoneNum,
}
